package com.myzhouye.biz.controller;/***
 *                    _ooOoo_
 *                   o8888888o
 *                   88" . "88
 *                   (| -_- |)
 *                    O\ = /O
 *                ____/`---'\____
 *              .   ' \\| |// `.
 *               / \\||| : |||// \
 *             / _||||| -:- |||||- \
 *               | | \\\ - /// | |
 *             | \_| ''\---/'' | |
 *              \ .-\__ `-` ___/-. /
 *           ___`. .' /--.--\ `. . __
 *        ."" '< `.___\_<|>_/___.' >'"".
 *       | | : `- \`.;`\ _ /`;.`/ - ` : | |
 *         \ \ `-. \_ __\ /__ _/ .-` / /
 * ======`-.____`-.___\_____/___.-`____.-'======
 *                    `=---='
 *
 * .............................................
 *          佛祖保佑             永无BUG
 */

import com.myzhouye.biz.bean.R;
import com.myzhouye.biz.dto.params.FactoryCreateParams;
import com.myzhouye.biz.dto.BaseFactory;
import com.myzhouye.biz.service.BaseFactoryService;
import com.myzhouye.biz.utils.SecurityUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * @program: demo1
 * @description:
 * @author: 那条蠢鱼
 * @create: 2025-09-29 11:27
 **/
@RestController
@RequestMapping("factory")
@RequiredArgsConstructor
@Tag(name = "工厂")
public class FactoryController {
    private final BaseFactoryService baseFactoryService;


    /**
     * 获取所有工厂
     * 普通用户使用
     * @return 工厂列表
     */
    @GetMapping("list")
    @Operation(summary = "获取所有工厂")
    public R<List<BaseFactory>> list() {
        return R.ok(baseFactoryService.getFactories().values().stream()
                .toList());
    }

    /**
     * 创建工厂
     * 调试用
     * @param params
     * @return
     */
    @Operation(summary = "创建工厂")
    @PostMapping
    public R<String> createFactory(FactoryCreateParams params) {
        String id = baseFactoryService.createFactory(params.getName(), params.getWarehouseSize(), params.getProductName(),params.getProductionSpeed(),params.getUserId());
        return R.ok(id);
    }

    /**
     * 根据模板id创建工厂
     * 普通用户使用
     * @param id 工厂模板ID
     * @return Mono<R<String>> 工厂ID（响应式返回）
     */
    @PostMapping("/createByTemplate/{id}")
    @Operation(summary = "根据模板id创建工厂")
    public Mono<R<String>> createFactoryByTemplate(@PathVariable String id) {
        // 响应式获取用户ID，避免阻塞
        return SecurityUtils.getCurrentUserId()
                .flatMap(userId -> Mono.fromCallable(() ->
                        baseFactoryService.createFactoryByTemplate(id, userId) // 传递userId到服务层
                ))
                .map(R::ok) // 成功响应
                .onErrorResume(e -> Mono.just(R.failed("创建工厂失败: " + e.getMessage()))); // 错误处理
    }

    @Operation(summary = "获取工厂资源数量")
    @GetMapping("/{id}/count")
    public R<Integer> getResourceCount(@PathVariable String id) {
        return R.ok(baseFactoryService.getResourceCount(id));
    }

    /**
     * 消耗工厂资源
     * @param id 工厂ID
     * @param count 消耗数量
     * @return 消耗数量
     */
    @PostMapping("/{id}/consume")
    @Operation(summary = "消耗工厂资源")
    public R<Integer> consumeResources(@PathVariable String id, @RequestParam int count) {
        int nums=baseFactoryService.consumeResources(id, count);
        return R.ok(nums);
    }

    @Operation(summary = "收集工厂资源到仓库")
    @PostMapping("/{id}/collect")
    public R collectToWarehouse(@PathVariable String id) {
        int collectCount=baseFactoryService.collectToWarehouse(id);
        return switch (collectCount) {
            case -1 -> R.failed("没有仓库");
            case -2 -> R.failed("仓库没有剩余空间");
            case -3 -> R.failed("工厂不存在");
            default -> R.ok(collectCount);
        };
    }

}
